package cn.qiyu5522.tk_ems.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.*;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.entity.dto.ResumeDeliveryRecordDTO;
import cn.qiyu5522.tk_ems.entity.vo.JobVO;
import cn.qiyu5522.tk_ems.entity.vo.ResumeDeliveryRecordVO;
import cn.qiyu5522.tk_ems.mapper.*;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.ResumeDeliveryRecordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生简历投递记录表 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-03-01
 */
@Service
public class ResumeDeliveryRecordServiceImpl extends ServiceImpl<ResumeDeliveryRecordMapper, ResumeDeliveryRecord> implements ResumeDeliveryRecordService {
    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private JobMapper jobMapper;
    @Resource
    private JobcategoryMapper jobcategoryMapper;


    @Override
    public R queryResumeDeliveryRecordByPageCondition(QueryParamDTO<ResumeDeliveryRecordDTO> queryParamDTO) {
        ResumeDeliveryRecordDTO condition = queryParamDTO.getCondition();
        IPage<ResumeDeliveryRecord> resumeDeliveryRecordIPage = new Page<>(queryParamDTO.getCurrentPage(),queryParamDTO.getPageSize());
        LambdaQueryWrapper<ResumeDeliveryRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据投递时间
        lambdaQueryWrapper.ge(ObjectUtil.isNotEmpty(condition.getDeliveryTimeStart()),ResumeDeliveryRecord::getDeliveryTime, condition.getDeliveryTimeStart())
                .le(ObjectUtil.isNotEmpty(condition.getDeliveryTimeEnd()),ResumeDeliveryRecord::getDeliveryTime, condition.getDeliveryTimeEnd());
        // 获取用户编号
        Object loginId = StpUtil.getLoginId();
        Long userId =Long.valueOf( ((String) loginId).split("-")[0]);
        List<String> roleList = StpUtil.getRoleList();
        boolean adminRole = roleList.stream().anyMatch(s -> "admin".equals(s));
        boolean companyRole = roleList.stream().anyMatch(s -> "company".equals(s));
        boolean studentRole = roleList.stream().anyMatch(s -> "student".equals(s));
        // 如果是管理员则全查
        if(adminRole){
            baseMapper.selectPage(resumeDeliveryRecordIPage,lambdaQueryWrapper);
        }else if(companyRole){
            // 根据公司编号，查询对应公司的简历投递状态
            lambdaQueryWrapper.eq(ResumeDeliveryRecord::getCompanyId,userId);
            baseMapper.selectPage(resumeDeliveryRecordIPage,lambdaQueryWrapper);
        }else if(studentRole){
            // 根据学生编号，查询对应学生的简历投递状态
            lambdaQueryWrapper.eq(ResumeDeliveryRecord::getStudentId,userId);
            baseMapper.selectPage(resumeDeliveryRecordIPage,lambdaQueryWrapper);
        }
        // 实体转VO
        List<ResumeDeliveryRecordVO> resumeDeliveryRecordVOS = objectMapper
                .convertValue(resumeDeliveryRecordIPage.getRecords(),
                        new TypeReference<List<ResumeDeliveryRecordVO>>() {
                });
        if(resumeDeliveryRecordVOS.size()==0){
            Map<String, Object> map = CustomMapResult.packagingResult(
                    new ArrayList(0),
                    queryParamDTO.getCurrentPage(),
                    queryParamDTO.getPageSize(),
                    resumeDeliveryRecordIPage.getTotal());
            return R.ok().data("resumeDeliveryIPage",map);
        }
        // 映射学生姓名
        List<Long> studentIds = resumeDeliveryRecordVOS.stream().map(ResumeDeliveryRecordVO::getStudentId).collect(Collectors.toList());
        List<Student> students = studentMapper.selectBatchIds(studentIds);
        for (Student student : students) {
            resumeDeliveryRecordVOS.forEach(resumeDeliveryRecordVO -> {
                if (resumeDeliveryRecordVO.getStudentId().equals(student.getId())) {
                    resumeDeliveryRecordVO.setStudentName(student.getName());
                }
            });
        }
        // 映射公司名称
        List<Long> companyIds = resumeDeliveryRecordVOS.stream().map(ResumeDeliveryRecordVO::getCompanyId).collect(Collectors.toList());
        List<Company> companies = companyMapper.selectBatchIds(companyIds);
        for (Company company : companies) {
            resumeDeliveryRecordVOS.forEach(resumeDeliveryRecordVO -> {
                if (resumeDeliveryRecordVO.getCompanyId().equals(company.getId())) {
                    resumeDeliveryRecordVO.setCompanyName(company.getName());
                }
            });
        }
        // 映射岗位名称
        // 根据岗位编号查询岗位名称
        List<Integer> jobIds = resumeDeliveryRecordVOS.stream().map(ResumeDeliveryRecordVO::getJobId).collect(Collectors.toList());
        List<Job> jobs = jobMapper.selectBatchIds(jobIds);
        // 根据岗位名称里放的值职位的编号,还需要去查询职位分类表中对应的id
        List<Integer> jobNameIds = jobs.stream().map(job -> Integer.valueOf(job.getName())).collect(Collectors.toList());
        List<JobCategory> jobCategories = jobcategoryMapper.selectBatchIds(jobNameIds);
        // job实体转jobVO
        List<JobVO> jobVOS = objectMapper.convertValue(jobs, new TypeReference<List<JobVO>>() {
        });
        for (JobCategory jobCategory : jobCategories) {
            jobVOS.forEach(jobVO -> {
                if(jobCategory.getId().equals(Integer.valueOf(jobVO.getName()))){
                    jobVO.setJobName(jobCategory.getName());
                }
            });
        }
        for (JobVO jobVO : jobVOS) {
            resumeDeliveryRecordVOS.forEach(resumeDeliveryRecordVO -> {
                if(resumeDeliveryRecordVO.getJobId().equals(jobVO.getId())){
                    resumeDeliveryRecordVO.setJobName(jobVO.getJobName());
                }
            });
        }
        Map<String, Object> map = CustomMapResult.packagingResult(
                resumeDeliveryRecordVOS,
                queryParamDTO.getCurrentPage(),
                queryParamDTO.getPageSize(),
                resumeDeliveryRecordIPage.getTotal());
        return R.ok().data("resumeDeliveryIPage",map);
    }

    @Override
    public R saveMore(List<ResumeDeliveryRecordDTO> resumeDeliveryRecordDTOs) {
        // DTO 转实体
        List<ResumeDeliveryRecord> resumeDeliveryRecords = objectMapper.convertValue(resumeDeliveryRecordDTOs, new TypeReference<List<ResumeDeliveryRecord>>() {
        });
        List<ResumeDeliveryRecord> collect = resumeDeliveryRecords.stream().map(resumeDeliveryRecord -> resumeDeliveryRecord.setDeliveryTime(LocalDateTime.now())).collect(Collectors.toList());

        Integer integer = baseMapper.insertBatchSomeColumn(collect);
        return integer>0?R.ok().message("添加成功"):R.error().message("添加失败");
    }
}
